<template>
  <div class="chat">
    <div class="list-pane">
      <div class="user-pane">
        <div class="user-count">
          <h2>当前在线人数：{{ userCount }}</h2>
        </div>
        <!-- 广播消息按钮（可选） -->
        <!--        <el-button @click="broadcastMessage">发布广播消息</el-button>-->
        <div class="user-list">
          <div class="user" v-for="user in userList" :key="user.userId">
            <el-image
                class="user-img"
                :src="user.avatar"
                @click="chatWithUser(user)"
            ></el-image>
            <!--如果id是自己，就显示成“我”-->
            <p v-if="user.userId===userId" class="username">我</p>
            <p v-else class="username">{{ user.userName }}</p>
          </div>
        </div>
      </div>
    </div>
    <div class="chat-pane">
      <div class="chat-header">
        <h2 v-if="receiverName===undefined">点击一个用户头像开始聊天吧！</h2>
        <h2 v-else>Chat With : {{ receiverName }}</h2>
      </div>
      <div class="chat-message" ref="chatHistory">
        <div class="user-message" v-for="message in messages" :key="message">
          <div class="img">
            <el-image
                v-if="userName === message.senderName"
                class="user-img"
                :src="receiverAvatar"
            ></el-image>
            <el-image
                v-else
                class="user-img"
                :src="senderAvatar"
            ></el-image>
          </div>
          <div class="message">
            <div class="username">
              <span v-if="userName === message.senderName">我</span>
              <span v-else>{{ message.senderName }}</span>
              <span class="time">{{ message.time }}</span>
            </div>
            <div :class="{'text': true, 'user-text': userName === message.senderName}">
              {{ message.msg }}
            </div>
          </div>
        </div>
      </div>
      <div class="chat-textarea">
        <el-input
            v-model="text"
            class="user-textarea"
            type="textarea"
            resize="none"
            @keydown.enter="sendButton"
        ></el-input>
        <el-button type="primary" class="send-button" @click="sendButton">发送</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import {onMounted, onUnmounted, ref} from "vue";
import router from "@/router";
import {ElMessageBox} from "element-plus";

let userName = ref();
let userId = ref();
let receiverId = ref();
let receiverName = ref();
let senderAvatar = ref();//我的头像
let receiverAvatar = ref();//聊天对象的头像
let socket;

onMounted(() => {
  console.log("ChatView 组件已激活");
  userId.value = sessionStorage.getItem('userId');
  userName.value = sessionStorage.getItem("userName");
  senderAvatar.value = sessionStorage.getItem("avatar");
  // 查询是否设置了昵称
  if (userName.value == null) {
    router.push("/message");
    return;
  }

  // 查询浏览器是否支持 WebSocket
  if (typeof WebSocket == "undefined") {
    alert("您的浏览器不支持 WebSocket");
    router.push("/message");
    return;
  }

  // 开启 WebSocket 服务
  let socketHost = "localhost";
  let socketPort = "8080";
  let socketUrl = "ws://" + socketHost + ":" + socketPort + "/socket/" + userId.value;
  socket = new WebSocket(socketUrl);

  // 连接服务器
  socket.onopen = () => {
    console.log("已连接至服务器");
  };

  // 浏览器接收服务端发送的消息
  socket.onmessage = (msg) => {
    let data = JSON.parse(msg.data);
    if (data.userList) {
      // 接收用户列表消息
      userList.value = data.userList;
      userCount.value = data.userList.length;
    } else if (data.messageList) {
      //添加到消息列表中
      messages.value.push(...data.messageList);
      scrollToEnd();
    } else if (data.msg === undefined) {
    } else {
      // 接收消息
      messages.value.push(data);
      // 获取节点
      scrollToEnd();
    }
  };
  // 关闭服务
  socket.onclose = () => {
    console.log("WebSocket 服务已关闭");
  };
  // 错误事件
  socket.onerror = () => {
    console.log("WebSocket 服务发生错误");
  };
});
const scrollToEnd = () => {
  // 获取节点
  let chatHistory = document.getElementsByClassName("chat-message")[0];
  if (chatHistory.scrollHeight >= chatHistory.clientHeight) {
    setTimeout(function () {
      //设置滚动条到最底部
      chatHistory.scrollTop = chatHistory.scrollHeight;
    }, 0);
  }
}
//退出时自动断开连接
onUnmounted(() => {
  socket.close();
})

const chatWithUser = (user) => {
  //先清空message
  messages.value = [];

  //设置聊天对象信息
  receiverId.value = user.userId;
  receiverName.value = user.userName;
  receiverAvatar.value = user.avatar;

  message.type = 0;
  message.receiverId = receiverId.value;
  message.senderId = userId.value;
  console.log(message)
  //获取mongo中两人的消息记录
  socket.send(JSON.stringify(message));
}
// 日期转换
const formatTime = (date) => {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();

  return (
      [year, month, day].map(formatNumber).join("-") +
      " " +
      [hour, minute, second].map(formatNumber).join(":")
  );
};
const formatNumber = (n) => {
  const s = n.toString();
  return s[1] ? s : "0" + s;
};

// 用户数量
let userCount = ref(0);

// 用户列表
let userList = ref([]);

// 信息框
let text = ref("");

// 信息列表
let messages = ref([]);

// 信息
let message = {
  id: null,
  read: false,
  type: 0, //0:获取消息记录，1:普通消息，2:群发消息
  time: "",
  msg: "",
  senderId: "",
  senderName: "",
  receiverId: "",
  receiverName: ""
};

// 发送信息
const sendButton = (event) => {
  event.preventDefault();

  if (receiverId.value === undefined) {
    ElMessageBox.alert(
        "请选择一个在线用户进行聊天",
        "提示", {
          confirmButtonText: "确定",
          type: "warning",
        });
    return;
  }

  if (text.value != null && text.value !== "" && userName.value != null) {
    message.type = 1;
    message.senderName = userName.value;
    message.time = formatTime(new Date());
    message.msg = text.value;
    // message.senderId = userId.value
    // message.receiverId = receiverId.value;
    message.receiverName = receiverName.value;

    socket.send(JSON.stringify(message));
    message.msg = "";
    text.value = "";
  }
};

</script>

<style scoped>
@import "../../assets/css/chat.css";
</style>
